package com.example.take_out_dish.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.take_out_dish.config.JwtConfig;
import com.example.take_out_dish.dto.DishDTO;
import com.example.take_out_dish.entity.Dish;
import com.example.take_out_dish.exceptions.BusinessException;
import com.example.take_out_dish.exceptions.enumetation.ResponseEnum;
import com.example.take_out_dish.mapper.DishMapper;
import com.example.take_out_dish.service.DishService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.take_out_dish.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 菜品管理 服务实现类
 * </p>
 *
 * @author yyyyys
 * @since 2024-07-01
 */
@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {
    @Resource
    private DishMapper dishMapper;
    @Resource
    private HttpServletRequest request;
    @Resource
    private JwtConfig jwtConfig;

    @Override
    public Page<DishDTO> pageWithCategoryName(int page, int pageSize, String name, String categoryId, Integer status) {
        Page<DishDTO> pageResult = new Page<>(page, pageSize);
        List<DishDTO> dishDTOList = dishMapper.selectDishDTOPage(pageResult, name, categoryId, status);
        pageResult.setRecords(dishDTOList);
        return pageResult;
    }

    @Override
    public void saveDish(Dish dish) {
        String token = request.getHeader("token");
        if (!JwtUtils.validateToken(token,jwtConfig.getKey())){
            throw new BusinessException(ResponseEnum.TOKEN_EXPIRED);
        }
        Claims claims = JwtUtils.parseJwt(token, jwtConfig.getKey());
        String name = claims.get("name", String.class);
        dish.setCode("123");
        dish.setCreateUser(name);
        dish.setUpdateUser(name);
        dish.setCreateTime(new Date());
        dish.setUpdateTime(new Date());
        save(dish);
    }

}
